package com.hhkj.captcha.common.handler;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.hhkj.captcha.common.cont.CaptchaConst;
import com.hhkj.captcha.common.manager.CaptchaManager;
import com.hhkj.captcha.model.extend.Captcha;
import com.hhkj.sms.SmsSender;
import com.hhkj.sms.common.cont.PlatformEnum;
import com.hhkj.sms.model.base.BaseSendParam;
import com.ruoyi.common.exception.GlobalException;

import java.util.Date;

/**
 * CaptchaHandler
 *
 * @author SERVER
 * @since 2024/3/28 11:37
 */
public interface CaptchaHandler {

    /**
     * 获取验证码管理器
     *
     * @return 验证码管理器
     */
    default CaptchaManager getCaptchaManager() {
        Object captchaManager = SpringUtil.getBean("CaptchaManager");
        if (ObjectUtil.isNull(captchaManager) ||
                !(captchaManager instanceof CaptchaManager)) {
            throw new GlobalException("验证码管理器暂未注册");
        }
        return (CaptchaManager) captchaManager;
    }

    /**
     * 对应处理编码
     *
     * @return 验证模块编码
     */
    default String getCode() {
        return "";
    }

    /**
     * 发送
     */
    default void send(String mobile) {

        this.beforeSend(mobile);
        // 2、查看缓存中是否有对应的手机号验证码缓存
        Captcha captcha
                = this.getCaptchaManager().getCaptcha(this.getCode(), mobile);
        // 3、判断是不是超过60s
        if (captcha != null) {
            long captchaSendingIntervalSecond = DateUtil.between(new Date(), captcha.getCreateTime(), DateUnit.SECOND);
            if (captchaSendingIntervalSecond < CaptchaConst.CAPTCHA_SENDING_INTERVAL_LIMIT_SECOND) {
                throw new GlobalException("验证码已发送，请 " + (CaptchaConst.CAPTCHA_SENDING_INTERVAL_LIMIT_SECOND - captchaSendingIntervalSecond) + "s 后再试");
            }
        }
        // 4、重新生成验证码
        captcha = this.getCaptchaManager().createCaptcha(this.getCode(), mobile);
        // 5、发送短信
        SmsSender.send(PlatformEnum.ALI_DA_YU, mobile, this.createCaptchaSmsBody(captcha));
    }

    /**
     * 短信发送前置处理
     *
     * @param mobile 手机号
     */
    void beforeSend(String mobile);

    /**
     * 根据验证码创建短信body
     *
     * @param captcha 验证码
     * @return 发送短信体
     */
    BaseSendParam createCaptchaSmsBody(Captcha captcha);

    /**
     * 校验验证码
     *
     * @param mobile      手机号
     * @param captchaCode 校验验证码
     */
    default void verify(String mobile, String sourceCode,  String captchaCode) {
        Captcha captcha = this.getCaptchaManager().getCaptcha(sourceCode, mobile);
        if (captcha == null || !captcha.getMobile().equals(mobile)) {
            throw new GlobalException("验证码无效！");
        }
        if (!captcha.getCaptcha().equals(captchaCode)) {
            throw new GlobalException("验证码错误！");
        }
    }
}
